var GameID = null;


function initPlayerInsertToGameWindow()
{
    modalWindowHandler.setWindowPosition('top');
    modalWindowHandler.setModalWindowTitle("Insert Players into Live Match");
    modalWindowHandler.setContent('getInsertPlayerIntoGameForm');
    $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
    //modalWindowHandler.openModalWindow();
    $( "#modalDialogWindow" ).dialog('open');
    //modalWindowHandler.AJAXCallbackFunction = ("setUpAddTeamModalWindow");
    // modalWindowHandler.openModalWindow();
    //setUpAddPlayerModalWindow();
    modalWindowHandler.setWindowWidth('650')
    sendRequest.setAction('getInsertPlayerIntoGameForm');
   
    sendRequest.setSendParameters({
        'gameID':GameID
    });
    $("#mask").load(sendRequest.serverURL,sendRequest.getSendData(),function (commentatorContent)
    {
        $( "#modalDialogWindow" ).children("#modalWindowContent").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>");
        $( "#modalDialogWindow" ).children("#modalWindowContent").hide();
        $( "#modalDialogWindow" ).children("#modalWindowContent").delay(1000).html($("#mask").html()).fadeIn('slow');
        $( "#modalDialogWindow" ).append("<div id=loadingScreen></div>");
        $("#mask").empty();
        $(".errorMessageDiv").hide();
        $(".responseDiv").hide();


        $(".isBowler").css({
            opacity: 0.2
        });
        $(".isCaptain").css({
            opacity: 0.2
        });
        // $(".isWicketKeeper").css({ opacity: 0.2 });
        setUpPlayerInsertionModalWindow();
    //setUpGameInsertGameModalWindow()
    });
}

function updatePlayerPrompt(isError,container,errtext)
{
    container.text(errtext);
    container.removeClass('ui-state-disabled');
    container.removeClass('ui-state-highlight');
    if (isError)
    {
        container.animate({
            'font-size': '1.2em',
            backgroundColor: "#aa0000",
            color: "#fff",

            'width': 250,
            height: 25
        }, 1000 );

        setTimeout(function() {
            container.removeAttr('style');
            container.addClass('ui-state-disabled');
            container.addClass('ui-state-highlight');
        }, 3500);
    }
    else
    {
        container.animate({
            'font-size': '1.2em',
            backgroundColor: "#4589D6",
            color: "#fff",

            'width': 250,
            height: 25
        }, 1000 );

        setTimeout(function() {
            container.removeAttr('style');
            container.addClass('ui-state-disabled');
            container.addClass('ui-state-highlight');
        }, 3500);
    }

}

function setUpPlayerInsertionModalWindow()
{
    $('.errorMessageDiv').show();


    $('#helpInfo').hide();
    $("#helpIcon").click(function(){
        if($('#helpInfo').is(":hidden"))
        {
            $('#helpInfo').slideDown('fast');
        }
        else{
            $('#helpInfo').slideUp('fast');
        }
        
    });
    //$(".isBowler").each(function(index, value) {
    //    //console.log('div' + index + ':' + $(this).attr('id'));
    //    $('.errorMessageDiv').append($(this).children().attr('name')+"<br>");
    //    $(".bowlerIcon #"+$(this).children().attr('name')).click(function(){
    //
    //    });
    //});
    $( "#sortable-homeTeamProspectivePlayers, #sortable-homeTeamPlayers" ).sortable({
        placeholder: "ui-state-highlight",
        items: "div:not(.ui-state-disabled)",
        connectWith: ".connectedSortable-homeTeam",
        receive: function (event,ui)
        {

            ui.item.children(".isCaptain").animate({
                opacity: 0.2
            }, 100);
            if ( $('#sortable-homeTeamPlayers').children("#sortable-homeTeam").children('.isWicketKeeper').length > 1)
            {

                updatePlayerPrompt(true,$("#emptySortable-homeTeam"),"Only one wicket keeper can play in a match.");
                $(ui.sender).sortable('cancel');
            }
            else if ( $('#sortable-homeTeamPlayers').children().length >= 2 && $('#sortable-homeTeamPlayers').children().length <= 4  )
            {
                updatePlayerPrompt(false,$("#emptySortable-homeTeam"),"Don't forget to set the batting order of players playing in this match.");
            }
            if ( $('#sortable-homeTeamPlayers').children().length > 12 ) {

                updatePlayerPrompt(true,$("#emptySortable-homeTeam"),"Only 11 players are allowed to play in match.");


                //ui.sender: will cancel the change. Useful in the 'receive' callback.
                $(ui.sender).sortable('cancel');

            }

        }
    }).disableSelection();

    $( "#sortable-awayTeamProspectivePlayers, #sortable-awayTeamPlayers" ).sortable({
        placeholder: "ui-state-highlight",
        items: "div:not(.ui-state-disabled)",
        connectWith: ".connectedSortable-awayTeam",
        receive: function (event,ui)
        {

            ui.item.children(".isCaptain").animate({
                opacity: 0.2
            }, 100);
            if ( $('#sortable-awayTeamPlayers').children("#sortable-awayTeam").children('.isWicketKeeper').length > 1)
            {

                updatePlayerPrompt(true,$("#emptySortable-awayTeam"),"Only one wicket keeper can play in a match.");
                $(ui.sender).sortable('cancel');
            }
            else if ( $('#sortable-awayTeamPlayers').children().length >= 2 && $('#sortable-awayTeamPlayers').children().length <= 4  )
            {
                updatePlayerPrompt(false,$("#emptySortable-awayTeam"),"Don't forget to set the batting order of players playing in this match.");
            }
            if ( $('#sortable-awayTeamPlayers').children().length > 12 ) {

                updatePlayerPrompt(true,$("#emptySortable-awayTeam"),"Only 11 players are allowed to play in match.");


                //ui.sender: will cancel the change. Useful in the 'receive' callback.
                $(ui.sender).sortable('cancel');

            }

        }
    }).disableSelection();

    $(".isCaptain").click(function (){

        var opacityOfIcon = $(this).css( 'opacity' );
        var icon = $(this);
        if (opacityOfIcon <= 0.2)
        {
            //icon.css({ opacity: 1 });
            var superParentContainerID = icon.parent().parent().attr('id');
            var parentContainerID = icon.parent().attr('id');
            $("#"+superParentContainerID).children("#"+parentContainerID).children(".isCaptain").animate({
                opacity: 0.2
            }, 100);
            // $(".isCaptain").animate({ opacity: 0.2 }, 100);
            icon.animate({
                opacity: 1
            }, 500);
        }
        else
        {
            icon.animate({
                opacity: 0.2
            }, 500);
        }


    });

    $('.isBowler').click(function(){
        var opacityOfIcon = $(this).css( 'opacity' );
        var icon = $(this);
        if (opacityOfIcon <= 0.2)
        {
            //icon.css({ opacity: 1 });
            icon.animate({
                opacity: 1
            }, 500);

        }
        else
        {
            icon.animate({
                opacity: 0.2
            }, 500);
        }

    
    });

    $("#modalDialogWindow").dialog( "option", "buttons", {
        "Set Players": function() {
            var bValid = true;

            var homeTeamContainer = $("#sortable-homeTeamActualContainer");
            var awayTeamContainer = $("#sortable-awayTeamActualContainer");
            var allFields = jQuery([]).add(homeTeamContainer).add(awayTeamContainer);
            allFields.removeClass('ui-state-error');


            var homeTeamSelectedBowlers = 0;
            var homeTeamSelectedCaptain = 0;
            var awayTeamSelectedBowlers = 0;
            var awayTeamSelectedCaptain = 0;

            $("#sortable-homeTeamPlayers").children("#sortable-homeTeam").children(".isBowler").each(function (i) {

                var opacityOfIcon = $(this).css( 'opacity' );
                if (opacityOfIcon > 0.2){
                    homeTeamSelectedBowlers +=1;
                }
            });

            $("#sortable-homeTeamPlayers").children("#sortable-homeTeam").children(".isCaptain").each(function (i) {

                var opacityOfIcon = $(this).css( 'opacity' );
                if (opacityOfIcon > 0.2){
                    homeTeamSelectedCaptain +=1;
                }
            });

            $("#sortable-awayTeamPlayers").children("#sortable-awayTeam").children(".isBowler").each(function (i) {

                var opacityOfIcon = $(this).css( 'opacity' );
                if (opacityOfIcon > 0.2){
                    awayTeamSelectedBowlers +=1;
                }
            });

            $("#sortable-awayTeamPlayers").children("#sortable-awayTeam").children(".isCaptain").each(function (i) {

                var opacityOfIcon = $(this).css( 'opacity' );
                if (opacityOfIcon > 0.2){
                    awayTeamSelectedCaptain +=1;
                }
            });

            if ( $('#sortable-homeTeamPlayers').children().length != 12 ) {

                bValid =false;
                formValidator.updateErrorMessage("Eleven Players are required to play a match. Please insert more players from the home team to play in the match.");
                homeTeamContainer.addClass('ui-state-error');
            }
            else if ( $('#sortable-awayTeamPlayers').children().length != 12 ) {

                bValid =false;
                formValidator.updateErrorMessage("Eleven Players are required to play a match. Please insert more players from the away team to play in the match.");
                awayTeamContainer.addClass('ui-state-error');
            } else if (homeTeamSelectedBowlers <=2 )
{
                bValid =false;
                formValidator.updateErrorMessage("Atleast three bowlers need to be selected to bowl in this match. Please insert more players from the home team to be bowlers in this match.");
                homeTeamContainer.addClass('ui-state-error');
            } else if (homeTeamSelectedCaptain != 1 )
{
                bValid =false;
                formValidator.updateErrorMessage("One player has to be selected to be captain for the team. Please insert only one player from the home team to be the captain in this match.");
                homeTeamContainer.addClass('ui-state-error');
            } else if (awayTeamSelectedBowlers <=2 )
{
                bValid =false;
                formValidator.updateErrorMessage("Atleast three bowlers need to be selected to bowl in this match. Please insert more players from the away team to be bowlers in this match.");
                awayTeamContainer.addClass('ui-state-error');
            } else if (awayTeamSelectedCaptain != 1 )
{
                bValid =false;
                formValidator.updateErrorMessage("One player has to be selected to be captain for the team. Please insert only one player from the away team to be the captain in this match.");
                awayTeamContainer.addClass('ui-state-error');
            }


            if (bValid)
            {

                //var result = $('#a_sortable').sortable('toArray');
                //var rankedTeamOrder = jQuery("#sortable-homeTeamPlayers").sortable('toArray').toString();
                //formValidator.updateErrorMessage(rankedTeamOrder);
                var homePlayersArray = [];
                var awayPlayersArray = [];
                $("#sortable-homeTeamPlayers").children("#sortable-homeTeam").each(function (batOrder) {
                    var playerPoolID = $(this).attr('name');
                    var isCaptain = null;
                    var isBowler = null;
                    if ($(this).children(".isCaptain").css( 'opacity' ) > 0.2)
                    {
                        isCaptain = 1;
                    }
                    else
                    {
                        isCaptain = 0;
                    }


                    if ($(this).children(".isBowler").css( 'opacity' ) > 0.2)
                    {
                        isBowler = 1;
                    }
                    else
                    {
                        isBowler = 0;
                    }
                    homePlayersArray.push({
                        'batOrder':batOrder+=1,
                        'playerPoolID':playerPoolID,
                        'isCaptain':isCaptain,
                        'isBowler':isBowler
                    });
                });

                $("#sortable-awayTeamPlayers").children("#sortable-awayTeam").each(function (batOrder) {
                    var playerPoolID = $(this).attr('name');
                    var isCaptain = null;
                    var isBowler = null;
                    if ($(this).children(".isCaptain").css( 'opacity' ) > 0.2)
                    {
                        isCaptain = 1;
                    }
                    else
                    {
                        isCaptain = 0;
                    }


                    if ($(this).children(".isBowler").css( 'opacity' ) > 0.2)
                    {
                        isBowler = 1;
                    }
                    else
                    {
                        isBowler = 0;
                    }
                    awayPlayersArray.push({
                        'batOrder':batOrder+=1,
                        'playerPoolID':playerPoolID,
                        'isCaptain':isCaptain,
                        'isBowler':isBowler
                    });
                });
             
                var playerDataToPost = {
                    "gameID":GameID,
                    "homeTeam":homePlayersArray,
                    "awayTeam":awayPlayersArray
                };
                //             playerDataToPost.push({"homeTeam":awayPlayersArray});
                //             playerDataToPost.push({"awayTeam":homePlayersArray});
                $( "#modalDialogWindow" ).children("#modalWindowContent").hide('blind',{},500);
                $( "#modalDialogWindow" ).children("#loadingScreen").hide();
                $( "#modalDialogWindow" ).children("#loadingScreen").html("<div style='margin-top : 50px; text-align: center; vertical-align: middle; height: 100%;'><img src="+$('#loadingImage').val()+" align='middle' alt='Loading Pic is Missing' /></div>").delay(700).show('bounce',{},1000);
                // var teamsPlayerORderJSON = JSON.stringify(playerDataToPost);
                sendRequest.setAction('registerPlayersToMatch');
                sendRequest.setSendParameters(playerDataToPost);

                var hiddenResponseDiv = jQuery('.responseDiv');
                hiddenResponseDiv.load(sendRequest.serverURL, sendRequest.getSendData(), function(){
                    hiddenResponseDiv.unbind();
                    hiddenResponseDiv.show();
                    var insertionResponse = (hiddenResponseDiv.html()).replace(/^\s*|\s*$/g,'');
                    // hiddenResponseDiv.html(registrationResponse).show();
                    hiddenResponseDiv.unbind();
                    if (insertionResponse == "1")
                    {
                        // $("#modalDialogWindow").dialog('close');
                        jQuery('.errorMessageDiv').html('');
                        //$( "#modalDialogWindow" ).children("#loadingScreen").delay(3500).fadeOut('slow');
                        $( "#modalDialogWindow" ).delay(3000).dialog('close');
                        //GameID = insertionResponse;
                        // initPlayerInsertToGameWindow();
                        openBallByBallCommentaryWindow();
                    //getBallStatsIndicator();
                    }
                    else
                    {
                        //$( "#modalDialogWindow" ).children("#loadingScreen").fadeOut('slow').html('');
                        $("#modalWindowContent").show();
                             
                        formValidator.updateErrorMessage("Insertion of players into match has failed. Players have already been entered to this match. Please insert other players to this match.");
                    }
                });
            //formValidator.updateErrorMessage(rankedTeamORderJSON);


            
            }

        },
        "Cancel": function() {
            $("#modalDialogWindow").dialog('close');
            jQuery('.errorMessageDiv').html('');
        }
    });
//});

}